package com.myapp.actions;

import com.myapp.bd.QueryBD;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.myapp.forms.ConnectionForm;
import java.sql.SQLException;
import javax.servlet.ServletContext;

public class ConnectionAction extends Action {

    public static final String TYPECO = "typeCo";

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws SQLException {
        ConnectionForm cf = (ConnectionForm) form;

        //instancie une connection avec la BD
        ServletContext context = getServlet().getServletContext();
        QueryBD connection = new QueryBD(context.getRealPath(""));

        String typeCo;
        //verifie validité des logine et mdp
        if ((connection.verif(cf.getLogin(), cf.getPwd())).equals("etudiant")) {
            typeCo = "etudiantCo";
            request.getSession().setAttribute(TYPECO, typeCo);
            int nCandidat = connection.recupNCandidatCo(cf.getLogin(), cf.getPwd());
            request.getSession().setAttribute("nCandidatCo", nCandidat);
            return mapping.findForward("etudiant");
        } else {
            if ((connection.verif(cf.getLogin(), cf.getPwd())).equals("enseignant")) {
                typeCo = "enseignantCo";
                request.getSession().setAttribute(TYPECO, typeCo);
                int nEnseignant = connection.recupNEnseignantCo(cf.getLogin(), cf.getPwd());
                request.getSession().setAttribute("nEnseignantCo", nEnseignant);
                return mapping.findForward("enseignant");
            } else {
                if ((connection.verif(cf.getLogin(), cf.getPwd())).equals("maitreDeStage")) {
                    typeCo = "maitreDeStageCo";
                    request.getSession().setAttribute(TYPECO, typeCo);
                    int nMaitreStage = connection.recupNMaitreStage(cf.getLogin(), cf.getPwd());
                    request.getSession().setAttribute("nMaitreStage", nMaitreStage);
                    return mapping.findForward("maitreDeStage");
                } else {
                    if ((connection.verif(cf.getLogin(), cf.getPwd())).equals("secretariat")) {
                        typeCo = "secretariatCo";
                        request.getSession().setAttribute(TYPECO, typeCo);
                        return mapping.findForward("secretariat");
                    } else {
                        return mapping.findForward("nonReconnu");
                    }
                }

            }
        }
    }
}
